/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package ma.projet.managedBean;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import javax.ejb.EJB;
import javax.enterprise.context.spi.Context;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import javax.faces.context.FacesContext;
import javax.servlet.http.Part;
import ma.projet.imports.inwi.transformationfinal_0_1.TransformationFinal;
import ma.projet.local.IncidentFacadeLocal;

/**
 *
 * @author Kamal
 */
@ManagedBean
@RequestScoped
public class DataBean {

    private Part file;
    @EJB
    private IncidentFacadeLocal ifl;

    /**
     * Creates a new instance of DataBean
     */
    public DataBean() {
    }

    public void setFile(Part file) {
        this.file = file;
    }

    public Part getFile() {
        return file;
    }

    public void upload() throws IOException {
        InputStream inputStream = file.getInputStream();
        FileOutputStream outputStream = new FileOutputStream("C://Excel//" + getFilename(file));
        byte[] buffer = new byte[4096];
        int bytesRead = 0;
        while (true) {
            bytesRead = inputStream.read(buffer);
            if (bytesRead > 0) {
                outputStream.write(buffer, 0, bytesRead);
            } else {
                break;
            }
        }
        String[] args = {};
        final TransformationFinal TransformationFinalClass = new TransformationFinal();
        TransformationFinal.setChemin("C://Excel//" + getFilename(file));
        int exitCode = TransformationFinalClass.runJobInTOS(args);
        FacesMessage msg = new FacesMessage("Importation ","Importation Réussite");
        FacesContext.getCurrentInstance().addMessage(null, msg);
        outputStream.close();
        inputStream.close();

    }

    private static String getFilename(Part part) {
        for (String cd : part.getHeader("content-disposition").split(";")) {
            if (cd.trim().startsWith("filename")) {
                String filename = cd.substring(cd.indexOf('=') + 1).trim().replace("\"", "");
                return filename.substring(filename.lastIndexOf('/') + 1).substring(filename.lastIndexOf('\\') + 1); // MSIE fix.
            }
        }
        return null;
    }

}
